/**
 * 处理评论接口的业务逻辑
 */
const getRandomInt = require('../utils')
const { createReview, getReviewList } = require('../service/review')
const { getBookInfo } = require('../service/book')

class ReviewController {
  // 新增评论
  async reviewBook(ctx, next) {
    // 获取数据
    const { book_id, user_id, rating, content } = ctx.request.body
    const review_id = getRandomInt(1, 10000000)

    if (!book_id) {
      ctx.body = {
        code: 400,
        msg: '图书编号不能为空'
      }
      return
    }
    if (!rating || !content) {
      ctx.body = {
        code: 400,
        msg: '评分或评论不能为空'
      }
      return
    }

    try {
      const temp = await getBookInfo({ book_id })
      if (temp.length === 0) {
        ctx.body = {
          code: 400,
          msg: '这本书不存在'
        }
        return
      }

      const res = await createReview(review_id, book_id, user_id, rating, content)
      ctx.body = {
        code: 200,
        msg: '评论成功',
        data: res
      }
    }
    catch (error) {
      console.error(error);
      ctx.body = {
        code: 500,
        msg: '评论失败',
        error: error.message
      };
    }
  }

  // 获取评论列表
  async getReview(ctx, next) {
    try {
      const res = await getReviewList()
      ctx.body = {
        code: 200,
        msg: '获取评论列表成功',
        data: res
      }
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: '获取评论列表失败',
        error: error.message
      };
    }
  }

}

module.exports = new ReviewController()
